package com.bigdata.es.elasticsearch;

import com.bigdata.es.conf.ConfigurationManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;


public class ElasticSearchUtils {

    private static final Logger logger = LogManager.getLogger(ElasticSearchUtils.class);

    //获取elasticsearch客户端对象
    public static TransportClient getClient() {
        Settings settings = Settings.builder()
                .put("cluster.name", ConfigurationManager.getProperty("cluster.name"))
                .build();
        //获取客户端对象
        TransportClient client = new PreBuiltTransportClient(settings);

        try{
            client.addTransportAddress(new TransportAddress(InetAddress.getByName(ConfigurationManager.getProperty("es_host"))
                    , ConfigurationManager.getInteger("es_cli_port")));
        }catch (UnknownHostException e){
            logger.error("An error occurred.", e);
        }
        return client;
    }

    /**
     * 删除索引
     */
    private static void deleteIndex(){
        String index = ConfigurationManager.getProperty("es_index");
        TransportClient client = getClient();
        client.admin().indices().prepareDelete(index).get();
        client.close();
    }

    public static void main(String[] args) {
        deleteIndex();
    }
}
